'use client';

import React, { useState } from 'react';
import Button from '@/components/ui/Button';
import { 
  Monitor,
  Cpu,
  HardDrive,
  Zap,
  Thermometer,
  Activity,
  Clock,
  AlertTriangle,
  CheckCircle,
  TrendingUp,
  Server,
  Eye,
  Download,
  Cloud,
  MemoryStick,
  Wifi
} from 'lucide-react';

interface SystemMetrics {
  nodeId: string;
  nodeName: string;
  nodeType: 'cloud' | 'edge';
  cpu: {
    usage: number;
    cores: number;
    temperature: number;
  };
  memory: {
    used: number;
    total: number;
    usage: number;
  };
  gpu: {
    usage: number;
    memory_used: number;
    memory_total: number;
    temperature: number;
    count: number;
  };
  network: {
    bandwidth_in: number;
    bandwidth_out: number;
    latency: number;
  };
  storage: {
    used: number;
    total: number;
    usage: number;
  };
  timestamp: string;
  status: 'normal' | 'warning' | 'critical';
}

interface TaskPerformance {
  taskId: string;
  taskName: string;
  status: 'running' | 'completed' | 'failed';
  executionTime: string;
  estimatedRemaining: string;
  throughput: number;
  efficiencyScore: number;
  bottlenecks: Array<{
    component: string;
    impact: 'low' | 'medium' | 'high';
    suggestion: string;
  }>;
  resourceUtilization: {
    cpu: number;
    memory: number;
    gpu: number;
  };
  progress: number;
}

export default function MonitoringPage() {
  const [activeTab, setActiveTab] = useState<'resources' | 'tasks' | 'alerts'>('resources');
  const [selectedTimeRange, setSelectedTimeRange] = useState('1h');
  
  const [systemMetrics] = useState<SystemMetrics[]>([
    {
      nodeId: 'cloud_1',
      nodeName: '北京数据中心',
      nodeType: 'cloud',
      cpu: { usage: 68, cores: 64, temperature: 52 },
      memory: { used: 312, total: 512, usage: 61 },
      gpu: { usage: 85, memory_used: 12, memory_total: 16, temperature: 72, count: 8 },
      network: { bandwidth_in: 1250, bandwidth_out: 890, latency: 12 },
      storage: { used: 1200, total: 2000, usage: 60 },
      timestamp: '2024-12-03 15:30:00',
      status: 'normal'
    },
    {
      nodeId: 'edge_1',
      nodeName: '变电站A边缘节点',
      nodeType: 'edge',
      cpu: { usage: 45, cores: 16, temperature: 48 },
      memory: { used: 28, total: 64, usage: 44 },
      gpu: { usage: 72, memory_used: 18, memory_total: 24, temperature: 68, count: 2 },
      network: { bandwidth_in: 85, bandwidth_out: 42, latency: 8 },
      storage: { used: 180, total: 500, usage: 36 },
      timestamp: '2024-12-03 15:30:00',
      status: 'normal'
    },
    {
      nodeId: 'edge_2',
      nodeName: '变电站B边缘节点',
      nodeType: 'edge',
      cpu: { usage: 92, cores: 16, temperature: 75 },
      memory: { used: 58, total: 64, usage: 91 },
      gpu: { usage: 96, memory_used: 22, memory_total: 24, temperature: 82, count: 1 },
      network: { bandwidth_in: 125, bandwidth_out: 78, latency: 15 },
      storage: { used: 320, total: 500, usage: 64 },
      timestamp: '2024-12-03 15:30:00',
      status: 'warning'
    }
  ]);

  const [taskPerformances] = useState<TaskPerformance[]>([
    {
      taskId: '1',
      taskName: '人员作业识别模型训练',
      status: 'running',
      executionTime: '2h 15m',
      estimatedRemaining: '45m',
      throughput: 150,
      efficiencyScore: 87.5,
      bottlenecks: [
        {
          component: 'data_loader',
          impact: 'medium',
          suggestion: '增加并行读取进程数'
        }
      ],
      resourceUtilization: { cpu: 68, memory: 61, gpu: 85 },
      progress: 75
    },
    {
      taskId: '2',
      taskName: '设备缺陷识别增量学习',
      status: 'completed',
      executionTime: '4h 20m',
      estimatedRemaining: '0m',
      throughput: 95,
      efficiencyScore: 92.3,
      bottlenecks: [],
      resourceUtilization: { cpu: 45, memory: 44, gpu: 72 },
      progress: 100
    },
    {
      taskId: '3',
      taskName: '大模型INT8量化任务',
      status: 'running',
      executionTime: '1h 35m',
      estimatedRemaining: '2h 10m',
      throughput: 25,
      efficiencyScore: 78.2,
      bottlenecks: [
        {
          component: 'quantization_engine',
          impact: 'high',
          suggestion: '优化量化算法并行度'
        },
        {
          component: 'memory_allocation',
          impact: 'medium',
          suggestion: '调整内存分配策略'
        }
      ],
      resourceUtilization: { cpu: 92, memory: 91, gpu: 96 },
      progress: 42
    }
  ]);

  const getStatusBadge = (status: string) => {
    switch (status) {
      case 'normal':
        return <span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800 border border-green-200">
          <span className="w-1.5 h-1.5 bg-green-600 rounded-full mr-1.5"></span>
          正常
        </span>;
      case 'warning':
        return <span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-yellow-100 text-yellow-800 border border-yellow-200">
          <span className="w-1.5 h-1.5 bg-yellow-600 rounded-full mr-1.5"></span>
          警告
        </span>;
      case 'critical':
        return <span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-red-100 text-red-800 border border-red-200">
          <span className="w-1.5 h-1.5 bg-red-600 rounded-full mr-1.5"></span>
          严重
        </span>;
      default:
        return <span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-800 border border-gray-200">
          {status}
        </span>;
    }
  };

  const getTaskStatusBadge = (status: string) => {
    switch (status) {
      case 'running':
        return <span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800 border border-blue-200">
          <span className="w-1.5 h-1.5 bg-blue-600 rounded-full mr-1.5"></span>
          运行中
        </span>;
      case 'completed':
        return <span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800 border border-green-200">
          <span className="w-1.5 h-1.5 bg-green-600 rounded-full mr-1.5"></span>
          已完成
        </span>;
      case 'failed':
        return <span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-red-100 text-red-800 border border-red-200">
          <span className="w-1.5 h-1.5 bg-red-600 rounded-full mr-1.5"></span>
          失败
        </span>;
      default:
        return <span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-800 border border-gray-200">
          {status}
        </span>;
    }
  };

  const getUsageColor = (usage: number) => {
    if (usage >= 90) return 'bg-red-500';
    if (usage >= 75) return 'bg-yellow-500';
    return 'bg-green-500';
  };

  const getBottleneckColor = (impact: string) => {
    switch (impact) {
      case 'high':
        return 'text-red-600 bg-red-100';
      case 'medium':
        return 'text-yellow-600 bg-yellow-100';
      case 'low':
        return 'text-green-600 bg-green-100';
      default:
        return 'text-gray-600 bg-gray-100';
    }
  };

  return (
    <div className="space-y-4">
      {/* 紧凑的标题栏 */}
      <div className="flex items-center justify-between rounded-lg px-4 py-3">
        <div>
          <h1 className="text-xl font-bold text-gray-900">训练监控</h1>
          <p className="text-sm text-gray-600 mt-0.5">系统资源与任务性能监控</p>
        </div>
        <div className="flex gap-2">
          <select
            className="px-3 py-1.5 text-sm border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-transparent"
            value={selectedTimeRange}
            onChange={(e) => setSelectedTimeRange(e.target.value)}
          >
            <option value="1h">1小时</option>
            <option value="6h">6小时</option>
            <option value="24h">24小时</option>
            <option value="7d">7天</option>
          </select>
          <Button variant="secondary" size="sm">
            <Download className="h-4 w-4 mr-1.5" />
            导出报告
          </Button>
        </div>
      </div>

      {/* 监控概览指标 */}
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-3">
        <div className="bg-gradient-to-br from-blue-50 to-blue-100 border border-blue-200 rounded-lg p-3">
          <div className="flex items-center justify-between">
            <div>
              <div className="text-xs font-medium text-blue-700 uppercase tracking-wide">活跃节点</div>
              <div className="text-2xl font-bold text-blue-900 mt-1">{systemMetrics.length}</div>
            </div>
            <Monitor className="h-6 w-6 text-blue-600" />
          </div>
        </div>
        
        <div className="bg-gradient-to-br from-green-50 to-green-100 border border-green-200 rounded-lg p-3">
          <div className="flex items-center justify-between">
            <div>
              <div className="text-xs font-medium text-green-700 uppercase tracking-wide">正常节点</div>
              <div className="text-2xl font-bold text-green-900 mt-1">
                {systemMetrics.filter(m => m.status === 'normal').length}
              </div>
            </div>
            <CheckCircle className="h-6 w-6 text-green-600" />
          </div>
        </div>
        
        <div className="bg-gradient-to-br from-yellow-50 to-yellow-100 border border-yellow-200 rounded-lg p-3">
          <div className="flex items-center justify-between">
            <div>
              <div className="text-xs font-medium text-yellow-700 uppercase tracking-wide">警告节点</div>
              <div className="text-2xl font-bold text-yellow-900 mt-1">
                {systemMetrics.filter(m => m.status === 'warning').length}
              </div>
            </div>
            <AlertTriangle className="h-6 w-6 text-yellow-600" />
          </div>
        </div>
        
        <div className="bg-gradient-to-br from-purple-50 to-purple-100 border border-purple-200 rounded-lg p-3">
          <div className="flex items-center justify-between">
            <div>
              <div className="text-xs font-medium text-purple-700 uppercase tracking-wide">运行任务</div>
              <div className="text-2xl font-bold text-purple-900 mt-1">
                {taskPerformances.filter(t => t.status === 'running').length}
              </div>
            </div>
            <Activity className="h-6 w-6 text-purple-600" />
          </div>
        </div>
      </div>

      {/* 选项卡导航 */}
      <div className="bg-white border border-gray-200 rounded-lg shadow-sm">
        <div className="flex border-b border-gray-200">
          {[
            { key: 'resources', label: '资源监控', icon: Monitor },
            { key: 'tasks', label: '任务性能', icon: Activity },
            { key: 'alerts', label: '告警信息', icon: AlertTriangle }
          ].map((tab) => {
            const IconComponent = tab.icon;
            return (
              <button
                key={tab.key}
                onClick={() => setActiveTab(tab.key as any)}
                className={`flex items-center px-4 py-3 text-sm font-medium transition-colors ${
                  activeTab === tab.key
                    ? 'text-blue-600 border-b-2 border-blue-600 bg-blue-50'
                    : 'text-gray-600 hover:text-gray-900 hover:bg-gray-50'
                }`}
              >
                <IconComponent className="h-4 w-4 mr-2" />
                {tab.label}
              </button>
            );
          })}
        </div>

        <div className="p-4">
          {activeTab === 'resources' && (
            <div className="space-y-4">
              {/* 资源监控表格 */}
              <div className="overflow-x-auto">
                <table className="min-w-full divide-y divide-gray-200">
                  <thead className="bg-gray-50">
                    <tr>
                      <th className="px-3 py-2 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">节点信息</th>
                      <th className="px-3 py-2 text-center text-xs font-medium text-gray-500 uppercase tracking-wider">状态</th>
                      <th className="px-3 py-2 text-center text-xs font-medium text-gray-500 uppercase tracking-wider">CPU</th>
                      <th className="px-3 py-2 text-center text-xs font-medium text-gray-500 uppercase tracking-wider">内存</th>
                      <th className="px-3 py-2 text-center text-xs font-medium text-gray-500 uppercase tracking-wider">GPU</th>
                      <th className="px-3 py-2 text-center text-xs font-medium text-gray-500 uppercase tracking-wider">网络</th>
                      <th className="px-3 py-2 text-center text-xs font-medium text-gray-500 uppercase tracking-wider">存储</th>
                      <th className="px-3 py-2 text-center text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
                    </tr>
                  </thead>
                  <tbody className="bg-white divide-y divide-gray-200">
                    {systemMetrics.map((metric) => (
                      <tr key={metric.nodeId} className="hover:bg-gray-50 transition-colors">
                        <td className="px-3 py-2">
                          <div className="flex items-center">
                            {metric.nodeType === 'cloud' ? (
                              <Cloud className="h-4 w-4 text-blue-500 mr-2" />
                            ) : (
                              <Server className="h-4 w-4 text-green-500 mr-2" />
                            )}
                            <div>
                              <div className="text-sm font-medium text-gray-900">{metric.nodeName}</div>
                              <div className="text-xs text-gray-500">{metric.nodeId}</div>
                            </div>
                          </div>
                        </td>
                        <td className="px-3 py-2 text-center">
                          {getStatusBadge(metric.status)}
                        </td>
                        <td className="px-3 py-2 text-center">
                          <div className="flex items-center justify-center space-x-1">
                            <div className="w-12 bg-gray-200 rounded-full h-1.5">
                              <div 
                                className={`h-1.5 rounded-full ${getUsageColor(metric.cpu.usage)}`}
                                style={{ width: `${metric.cpu.usage}%` }}
                              ></div>
                            </div>
                            <span className="text-xs font-medium">{metric.cpu.usage}%</span>
                          </div>
                          <div className="text-xs text-gray-500 mt-0.5">{metric.cpu.cores}核</div>
                        </td>
                        <td className="px-3 py-2 text-center">
                          <div className="flex items-center justify-center space-x-1">
                            <div className="w-12 bg-gray-200 rounded-full h-1.5">
                              <div 
                                className={`h-1.5 rounded-full ${getUsageColor(metric.memory.usage)}`}
                                style={{ width: `${metric.memory.usage}%` }}
                              ></div>
                            </div>
                            <span className="text-xs font-medium">{metric.memory.usage}%</span>
                          </div>
                          <div className="text-xs text-gray-500 mt-0.5">{metric.memory.used}/{metric.memory.total}GB</div>
                        </td>
                        <td className="px-3 py-2 text-center">
                          <div className="flex items-center justify-center space-x-1">
                            <div className="w-12 bg-gray-200 rounded-full h-1.5">
                              <div 
                                className={`h-1.5 rounded-full ${getUsageColor(metric.gpu.usage)}`}
                                style={{ width: `${metric.gpu.usage}%` }}
                              ></div>
                            </div>
                            <span className="text-xs font-medium">{metric.gpu.usage}%</span>
                          </div>
                          <div className="text-xs text-gray-500 mt-0.5">{metric.gpu.count}张卡</div>
                        </td>
                        <td className="px-3 py-2 text-center">
                          <div className="text-xs text-gray-900">
                            <div>↓{metric.network.bandwidth_in}MB/s</div>
                            <div>↑{metric.network.bandwidth_out}MB/s</div>
                          </div>
                          <div className="text-xs text-gray-500">{metric.network.latency}ms</div>
                        </td>
                        <td className="px-3 py-2 text-center">
                          <div className="flex items-center justify-center space-x-1">
                            <div className="w-12 bg-gray-200 rounded-full h-1.5">
                              <div 
                                className={`h-1.5 rounded-full ${getUsageColor(metric.storage.usage)}`}
                                style={{ width: `${metric.storage.usage}%` }}
                              ></div>
                            </div>
                            <span className="text-xs font-medium">{metric.storage.usage}%</span>
                          </div>
                          <div className="text-xs text-gray-500 mt-0.5">{metric.storage.used}/{metric.storage.total}GB</div>
                        </td>
                        <td className="px-3 py-2 text-center">
                          <Button size="sm" variant="secondary">
                            <Eye className="h-3 w-3" />
                          </Button>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          )}

          {activeTab === 'tasks' && (
            <div className="space-y-4">
              {/* 任务性能表格 */}
              <div className="overflow-x-auto">
                <table className="min-w-full divide-y divide-gray-200">
                  <thead className="bg-gray-50">
                    <tr>
                      <th className="px-3 py-2 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">任务信息</th>
                      <th className="px-3 py-2 text-center text-xs font-medium text-gray-500 uppercase tracking-wider">状态</th>
                      <th className="px-3 py-2 text-center text-xs font-medium text-gray-500 uppercase tracking-wider">进度</th>
                      <th className="px-3 py-2 text-center text-xs font-medium text-gray-500 uppercase tracking-wider">效率分数</th>
                      <th className="px-3 py-2 text-center text-xs font-medium text-gray-500 uppercase tracking-wider">资源利用率</th>
                      <th className="px-3 py-2 text-center text-xs font-medium text-gray-500 uppercase tracking-wider">吞吐量</th>
                      <th className="px-3 py-2 text-center text-xs font-medium text-gray-500 uppercase tracking-wider">瓶颈</th>
                    </tr>
                  </thead>
                  <tbody className="bg-white divide-y divide-gray-200">
                    {taskPerformances.map((task) => (
                      <tr key={task.taskId} className="hover:bg-gray-50 transition-colors">
                        <td className="px-3 py-2">
                          <div>
                            <div className="text-sm font-medium text-gray-900">{task.taskName}</div>
                            <div className="text-xs text-gray-500">执行时间: {task.executionTime}</div>
                            {task.estimatedRemaining !== '0m' && (
                              <div className="text-xs text-gray-500">剩余: {task.estimatedRemaining}</div>
                            )}
                          </div>
                        </td>
                        <td className="px-3 py-2 text-center">
                          {getTaskStatusBadge(task.status)}
                        </td>
                        <td className="px-3 py-2 text-center">
                          <div className="w-full">
                            <div className="flex items-center justify-center mb-1">
                              <span className="text-sm font-medium text-gray-900">{task.progress}%</span>
                            </div>
                            <div className="w-full bg-gray-200 rounded-full h-1.5">
                              <div 
                                className={`h-1.5 rounded-full transition-all duration-300 ${
                                  task.status === 'completed' ? 'bg-green-600' : 
                                  task.status === 'failed' ? 'bg-red-600' : 
                                  'bg-blue-600'
                                }`}
                                style={{ width: `${task.progress}%` }}
                              ></div>
                            </div>
                          </div>
                        </td>
                        <td className="px-3 py-2 text-center">
                          <div className="text-sm font-semibold text-green-600">{task.efficiencyScore}%</div>
                        </td>
                        <td className="px-3 py-2 text-center">
                          <div className="text-xs space-y-0.5">
                            <div>CPU: {task.resourceUtilization.cpu}%</div>
                            <div>内存: {task.resourceUtilization.memory}%</div>
                            <div>GPU: {task.resourceUtilization.gpu}%</div>
                          </div>
                        </td>
                        <td className="px-3 py-2 text-center">
                          <div className="text-sm font-medium text-gray-900">{task.throughput}</div>
                          <div className="text-xs text-gray-500">样本/秒</div>
                        </td>
                        <td className="px-3 py-2 text-center">
                          {task.bottlenecks.length > 0 ? (
                            <div className="space-y-1">
                              {task.bottlenecks.slice(0, 2).map((bottleneck, index) => (
                                <span
                                  key={index}
                                  className={`inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium ${getBottleneckColor(bottleneck.impact)}`}
                                >
                                  {bottleneck.component}
                                </span>
                              ))}
                              {task.bottlenecks.length > 2 && (
                                <div className="text-xs text-gray-500">+{task.bottlenecks.length - 2}个</div>
                              )}
                            </div>
                          ) : (
                            <span className="text-xs text-gray-400">无</span>
                          )}
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          )}

          {activeTab === 'alerts' && (
            <div className="text-center py-8">
              <AlertTriangle className="h-12 w-12 text-gray-400 mx-auto mb-4" />
              <h3 className="text-lg font-medium text-gray-900 mb-2">暂无告警信息</h3>
              <p className="text-gray-600">系统运行正常，没有发现异常情况</p>
            </div>
          )}
        </div>

        {/* 底部统计汇总 */}
        <div className="border-t border-gray-200 bg-gray-50 px-4 py-3">
          <div className="flex items-center justify-between text-sm text-gray-600">
            <div className="flex items-center gap-6">
              <span>监控节点: {systemMetrics.length}</span>
              <span>运行任务: {taskPerformances.filter(t => t.status === 'running').length}</span>
              <span>更新时间: {systemMetrics[0]?.timestamp}</span>
            </div>
            <div className="flex items-center gap-6">
              <span>平均CPU: {Math.round(systemMetrics.reduce((sum, m) => sum + m.cpu.usage, 0) / systemMetrics.length)}%</span>
              <span>平均内存: {Math.round(systemMetrics.reduce((sum, m) => sum + m.memory.usage, 0) / systemMetrics.length)}%</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
} 